/*
    Copyright  Louis CHEREL cherel.louis@gmail.com  
    This file is part of Agenda de l'Efrei.

    Agenda de l'Efrei is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Agenda de l'Efrei is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Agenda de l'Efrei.  If not, see <http://www.gnu.org/licenses/>.
 */

package fr.efrei.AgendaEfrei;


import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.support.v13.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.TableLayout;
import android.widget.Toast;

public class ViewNotes extends Activity implements ActionBar.OnNavigationListener,ViewPager.OnPageChangeListener{

    private static boolean isNotesUpdaterLaunched=false;
    private static boolean isshowNotesLaunched=false;
    private static boolean isUpdateNeeded=false;
    private static int mNumPages=-1;
    private static int isUpdateError=0;
    private ActionBar mActionbar=null;
    protected MenuItem mProgressbar=null;
    private PagerAdapter mPagerAdapter;
    private ViewPager mPager;
    protected TableLayout tl;
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {   // print the action bar
        super.onCreateOptionsMenu(menu);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.notes_menu, menu);
        
        return true;
    }
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(null);
        setContentView(R.layout.notes);
        mActionbar = getActionBar();
        mActionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
        mActionbar.setTitle("");
        mPager = (ViewPager)findViewById(R.id.pager);
        updateUI(null,false);
        
    }
    
    @Override
    public void onSaveInstanceState(Bundle outState){
        if(mPager!=null){
            mPager.removeAllViews();
        }
    }
    
    private void updateUI(MenuItem item,Boolean isRefresh){
        Log.v("ViewNotes","activity started");
        new AsyncTask<Object,Integer,Void>(){
            private Activity mParent;
            private ViewPager mPager;
            private MenuItem mItem;
            private ActionBar mActionbar;
            private boolean isRefresh;
            @Override
            protected Void doInBackground(Object... list) {
                Integer nombre_semestres;
                mParent = (Activity) list[0];
                mPager = (ViewPager) list[1];
                mItem = (MenuItem) list[2];
                mActionbar = (ActionBar) list[3];
                isRefresh = (Boolean) list[4];
                if(!isRefresh){
                    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(mParent);  // get User's Preferences
                    nombre_semestres = sharedPref.getInt("nombre_semestres",-1);
                    if(nombre_semestres!=-1){
                        ViewNotes.setNumPages(nombre_semestres);
                        Log.v("ViewNotes","nombre_semestres="+nombre_semestres);
                    }
                }
                while(ViewNotes.getNumPages()==-1 && ViewNotes.getIsUpdateError()==0){}
                nombre_semestres = ViewNotes.getNumPages();
                publishProgress(nombre_semestres);
                
                return null;
            }
            
            @Override
            protected void onProgressUpdate(Integer... nb_semestres){
		int numPages = nb_semestres[0];
                String[] semesters=null;
                Toast toast=null;
		try{
                    if(numPages!=-1 && ViewNotes.getIsUpdateError()==0){
                        Log.v("ViewNotes","Loading...");
                        mPagerAdapter = new ViewSemesterAdapter(mParent.getFragmentManager());
                        try{
                            mPager.setAdapter(mPagerAdapter);
                            mPager.setOnPageChangeListener((ViewPager.OnPageChangeListener)mParent);
                            mPager.setCurrentItem(numPages-1);
                            mPager.setOffscreenPageLimit(ViewNotes.getNumPages());
                        }catch(Exception e){
                            Log.v("ViewNotes","erreur mPager:"+e.toString());
                        }
                        
                        
                        semesters = new String[numPages];
                        for(int i=numPages;i>0;i--){
                            semesters[numPages-i]= "Semestre "+i;
                        }
                        toast = Toast.makeText(mParent, "Glissez vers la droite pour accéder à vos anciens semestres", Toast.LENGTH_LONG);
                    }
                    else if(ViewNotes.getIsUpdateError()==21){
                        toast = Toast.makeText(mParent, "entrez vos identifiants dans 'Préférences'", Toast.LENGTH_LONG);
                    }
                    else if(ViewNotes.getIsUpdateError()!=0){
                        toast = Toast.makeText(mParent, "erreur de chargement n°"+ViewNotes.getIsUpdateError(), Toast.LENGTH_LONG);
                    }
                    else{
                        toast = Toast.makeText(mParent, "Rechargez vos notes.", Toast.LENGTH_LONG);
                    }
                    Log.v("ViewNotes","Loaded.");
                }catch(Exception e){
                    toast = Toast.makeText(mParent, "Chargement échoué ("+e.toString()+"). Veuillez recharger vos notes.", Toast.LENGTH_LONG);
                }finally{
                    toast.show();
                    if(semesters==null){
                        semesters = new String[1];
                        semesters[0]="      ";
                    }
                    if(mItem!=null){
                        mItem.collapseActionView();
                        mItem.setActionView(null);
                    }
                    ArrayAdapter<CharSequence> adapter = new ArrayAdapter(mParent, R.layout.spinner, semesters);
                    mActionbar.setListNavigationCallbacks(adapter,(ActionBar.OnNavigationListener)mParent);
                    mActionbar.setSelectedNavigationItem(0);
                }
            }
        }.execute(this,mPager,item,mActionbar,isRefresh);
    }

    
    @Override
    public void onPause(){
        MainActivity.setIsMainActivityShown(true);
        super.onStop();
    }
    
    @Override
    public void onWindowFocusChanged(boolean hasFocus){
        super.onWindowFocusChanged(hasFocus);
    }
    
    public void getNotes(){
        Log.v("ViewNotes","getNotes "+ViewNotes.getIsNotesUpdaterLaunched());
        if(ViewNotes.getIsNotesUpdaterLaunched()==false){
            new NotesUpdater(this).execute();
        }
        else{
            Toast toast = Toast.makeText(this, "Notes en cours de chargement...", Toast.LENGTH_SHORT);
            toast.show();
        }
    }
    
    public static void setIsNotesUpdaterLaunched(boolean in){
        isNotesUpdaterLaunched=in;
        Log.v("NotesUpdater","started:"+isNotesUpdaterLaunched);
    }
    
    public static boolean getIsNotesUpdaterLaunched(){
        return isNotesUpdaterLaunched;
    }
    
    public static void setIsshowNotesLaunched(boolean in){
        isshowNotesLaunched=in;
        Log.v("showNotes","started:"+isshowNotesLaunched);
    }
    
    public static boolean getIsshowNotesLaunched(){
        return isshowNotesLaunched;
    }

    public static void setIsUpdateNeeded(boolean b){
        isUpdateNeeded=b;
        Log.v("isUpdateNeeded",""+isUpdateNeeded);
    }
    
    public static boolean getIsUpdateNeeded(){
        return isUpdateNeeded;
    }
    
    public static void setIsUpdateError(int i){
        isUpdateError=i;
        Log.v("isUpdateError",""+isUpdateError);
    }
    
    public static int getIsUpdateError(){
        return isUpdateError;
    }
    
    public static void setNumPages(int i){
        mNumPages=i;
        Log.v("mNumPages",""+mNumPages);
    }
    
    public static int getNumPages(){
        return mNumPages;
    }
    
    
    public void onTabClick(MenuItem item)
    {
        
        if(item.getTitle().equals("Préférences")) {
            Intent intent_preferences = new Intent(this, Preferences.class);
            startActivity(intent_preferences);
        }
        else if(item.getTitle().equals("Crédits")) {
            Intent intent_credits = new Intent(this, Credits.class);
            startActivity(intent_credits);
        }
        else if(item.getTitle().equals("Rafraichir")) {
            item.setActionView(R.layout.progressbar);
            item.expandActionView();
            mProgressbar=item;
            
            getNotes();
            updateUI(item,true);
        }
    }

    public boolean onNavigationItemSelected(int itemPosition, long itemId) {
        if(mPager!=null){
            mPager.setCurrentItem(getNumPages()-1-itemPosition);
            return true;
        }
        else{
            return false;
        }
    }

    public void onPageScrolled(int i, float f, int i1) {
    }

    public void onPageSelected(int i) {
    }

    public void onPageScrollStateChanged(int i) {
        if(mActionbar!=null && i==0){
            mActionbar.setSelectedNavigationItem(getNumPages()-1-mPager.getCurrentItem());
        }
    }
    
    private class ViewSemesterAdapter extends FragmentStatePagerAdapter {
        public ViewSemesterAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            position = position+1;
            return new ViewSemesterFragment(position);
        }

        @Override
        public int getCount() {
            return mNumPages;
        }
    }

    
}
